#pragma once
#include <vector>
#include <queue>
#include <utility>
#include "Mutex.hpp"
#include "Log.hpp"
#include "Thread.hpp"
#include "Cond.hpp"

namespace ThreadPoolModule
{
    using namespace MutexModule;
    using namespace LogModule;
    using namespace ThreadModule;
    using namespace CondModule;

    const int defaultnum = 5;

    template <class T>
    class ThreadPool
    {
        void WakeUpOne()
        {
            _cond.Notify();
            LOG(LogLevel::INFO) << "唤醒了一个线程";
        }

        void WakeUpAll()
        {
            LOG(LogLevel::INFO) << "唤醒了所有线程";
            _cond.NotifyAll();            
        }

        void Start()
        {
            if (_isrunning)
                return;
            _isrunning = true;
            for (int i = 0; i < _num; i++)
                _threads[i].start();
        }

        // 单例模式拷贝赋值禁用，构造私有
        ThreadPool(const ThreadPool<T> &) = delete;

        ThreadPool &operator=(const ThreadPool<T> &) = delete;

        ThreadPool(int num = defaultnum) : _num(num), _isrunning(false)
        {
            // 创建线程对象，待启动
            int cnt = num;
            while (cnt--)
            {
                _threads.push_back(std::function<void()>([this]()
                                                         { HandlerTask(); }));
            }
        }

    public:
        static ThreadPool<T> *GetInstance()
        {
            if(_instance==nullptr)
            {
                //对象已经创建后，每次获取单例都需要加锁后判断效率太低
                MutexGuard mg(_lock);
                if (_instance == nullptr)
                {
                    LOG(LogLevel::INFO)<<"创建了单例对象...";
                    _instance = new ThreadPool<T>();
                    _instance->Start();
                }
            }
            LOG(LogLevel::INFO)<<"获取了单例对象...";
            return _instance;
        }

        void HandlerTask()
        {
            char namebuffer[128];
            pthread_getname_np(pthread_self(), namebuffer, sizeof(namebuffer));
            while (true)
            {
                T t;
                {
                    MutexGuard mg(_mutex);
                    // 无任务&&运行状态 ->等待
                    while (_taskq.empty() && _isrunning)
                    {
                        _sleep++;
                        _cond.Wait(_mutex);
                        _sleep--;
                    }
                    // 无任务&&非运行状态 ->退出
                    if (_taskq.empty() && !_isrunning)
                    {
                        LOG(LogLevel::INFO) << namebuffer << "线程终止了";
                        break;
                    }
                    t = move(_taskq.front());
                    _taskq.pop();
                    t();
                }
            }
        }

        template <class T1>
        bool Equeue(T1 &&t)
        {
            // 非运行状态不能入入队列了
            if (!_isrunning)
                return false;
            {
                MutexGuard mg(_mutex);
                _taskq.push(std::forward<T1>(t));
                if (_sleep)
                    WakeUpOne();
            }
            return true;
        }

        void Stop()
        {
            // 不能直接强制cancle所有线程需要将当前的任务处理完
            if (!_isrunning)
                return;
            _isrunning = false;

            // 唤醒所有线程,执行完任务退出
            WakeUpAll();
        }

        void Join()
        {
            for (int i = 0; i < _num; i++)
                _threads[i].join();
        }

    private:
        bool _isrunning;
        std::vector<thread> _threads;
        int _num;
        std::queue<T> _taskq;
        Cond _cond;
        int _sleep;
        Mutex _mutex;

        static ThreadPool<T> *_instance;
        static Mutex _lock;
    };

    template<class T>
    ThreadPool<T>* ThreadPool<T>::_instance=nullptr;

    template<class T>
    Mutex ThreadPool<T>::_lock;
};